<template>
  <!-- 1审核人和2抄送人5发起人 -->
  <div
    class="node-wrap"
    v-if="
      (nodeConfig.pointType && nodeConfig.pointType < 3) ||
      nodeConfig.pointType === 5
    "
  >
    <!-- :class="(nodeConfig.pointType == 0 ? 'start-node ' : '') + (nodeConfig.error ? 'active error' : '')" -->
    <div class="node-wrap-box">
      <div
        class="title"
        :style="`background: rgb(${bgColors[nodeConfig.pointType]});`"
      >
        <span v-if="nodeConfig.pointType == 0">{{ nodeConfig.pointName }}</span>
        <template v-else>
          <span class="iconfont">{{
            nodeConfig.pointType == 1 ? '' : ''
          }}</span>
          <input
            v-if="isInput"
            type="text"
            class="ant-input editable-title-input"
            @blur="blurEvent()"
            v-focus
            v-model="nodeConfig.pointName"
            :placeholder="defaultText"
          />
          <span v-else class="editable-title" @click="clickEvent()">{{
            nodeConfig.pointName
          }}</span>
          <i
            class="anticon anticon-close close"
            @click="delNode(nodeConfig.id)"
          ></i>
        </template>
      </div>
      <div class="content" @click="setPerson('', nodeConfig.pointType)">
        <div class="text">
          <span class="placeholder" v-if="!showText"
            >请选择{{ defaultText }}</span
          >
          {{ showText }}
        </div>
        <i class="anticon anticon-right arrow"></i>
      </div>
      <!-- <div class="error_tip" v-if="nodeConfig.error">
                <i class="anticon anticon-exclamation-circle"></i>
            </div> -->
    </div>
    <AddNode
      :id="nodeConfig.id"
      @addNode="addNodeData"
      :childNodeP="nodeConfig"
    />
  </div>
  <!-- 4条件分支 -->
  <div
    class="branch-wrap"
    v-if="
      typeof nodeConfig.conditionNodes === 'object' &&
      nodeConfig.conditionNodes.length > 0
    "
  >
    <div class="branch-box-wrap">
      <div class="branch-box">
        <button
          class="add-branch"
          @click="addTerm(nodeConfig.conditionNodes[0])"
        >
          添加条件
        </button>
        <div
          class="col-box"
          v-for="(item, index) in nodeConfig.conditionNodes"
          :key="index"
        >
          <div class="condition-node">
            <div class="condition-node-box">
              <div class="auto-judge" :class="item.error ? 'error active' : ''">
                <div
                  class="sort-left"
                  v-if="index != 0"
                  @click="arrTransfer(index, -1)"
                >
                  &lt;
                </div>
                <div class="title-wrapper">
                  <input
                    v-if="isInputList[index]"
                    type="text"
                    class="ant-input editable-title-input"
                    @blur="blurEvent(index)"
                    @focus="(e:any)=>e.currentTarget.select()"
                    v-focus
                    v-model="item.pointName"
                  />
                  <span
                    v-else
                    class="editable-title"
                    @click="clickEvent(index)"
                    >{{ item.pointName }}</span
                  >
                  <span
                    class="priority-title"
                    @click="setPerson(item.priority, item.pointType)"
                    >优先级{{ item.priority }}</span
                  >
                  <i
                    class="anticon anticon-close close"
                    @click="delTerm(item, index)"
                  ></i>
                </div>
                <div
                  class="sort-right"
                  v-if="index != nodeConfig.conditionNodes.length - 1"
                  @click="arrTransfer(index, 1)"
                >
                  &gt;
                </div>
                <div
                  class="content"
                  @click="setPerson(item.priority, item.pointType)"
                >
                  {{ $func.conditionStr(nodeConfig, index) }}
                </div>
                <!-- <div class="error_tip" v-if="item.error">
                                    <i class="anticon anticon-exclamation-circle"></i>
                                </div> -->
              </div>
              <AddNode
                :id="item.id"
                @addNode="addNodeData"
                :childNodeP="item"
              />
            </div>
          </div>
          <TreeItem
            v-if="item.childNode"
            @addNode="addNodeData"
            v-model:nodeConfig="item.childNode"
            @delNode="delNode"
          />
          <template v-if="index == 0">
            <div class="top-left-cover-line"></div>
            <div class="bottom-left-cover-line"></div>
          </template>
          <template v-if="index == nodeConfig.conditionNodes.length - 1">
            <div class="top-right-cover-line"></div>
            <div class="bottom-right-cover-line"></div>
          </template>
        </div>
      </div>
      <AddNode
        :id="nodeConfig.id"
        :type="3"
        @addNode="addNodeData"
        :childNodeP="nodeConfig"
      />
    </div>
  </div>
  <TreeItem
    v-if="nodeConfig.childNode"
    @addNode="addNodeData"
    v-model:nodeConfig="nodeConfig.childNode"
    @delNode="delNode"
  />
</template>

<script setup lang="ts">
import { onMounted, ref, watch, getCurrentInstance, computed } from 'vue';
import $func from './plugins/preload';
import { useFlowStore } from '@/store/index';
import AddNode from './addNode.vue';
import type { FlowPanelPoint, FlowTree } from '@/apis/flowPanelPoint/type';
import { isArray } from 'lodash';

const flowStore = useFlowStore();
let emits = defineEmits([
  'update:flowPermission',
  'update:nodeConfig',
  'addNode',
  'delNode'
]);
let _uid = getCurrentInstance()?.uid;

const props = withDefaults(
  defineProps<{
    nodeConfig?: FlowTree;
  }>(),
  {
    nodeConfig: () => ({})
  }
);
//添加节点
const addNodeData = (data: FlowPanelPoint) => {
  emits('addNode', data);
};
// 添加条件
const addTerm = (data: FlowPanelPoint) => {
  const { processId, relDescDetail } = data;
  const len = props.nodeConfig?.conditionNodes?.length;
  const newConditionNode: FlowPanelPoint = {
    pointName: `条件${len}`,
    pointType: 4,
    priority: len,
    processId
  };

  if (!relDescDetail) return;
  newConditionNode.relDescDetail = [];
  relDescDetail.forEach((item: any) => {
    const { previousStep, previousStepType, nextStep, nextStepType } = item;
    if (!isArray(newConditionNode.relDescDetail)) return;
    newConditionNode.relDescDetail.push({
      previousStep,
      previousStepType,
      nextStep,
      nextStepType
    });
  });

  // resetConditionNodesErr()
  emits('addNode', newConditionNode);
};
const delNode = (conditionId: number, changePoints: FlowPanelPoint) => {
  delNodeRelevancy();
  // emits("delNode", conditionId, changePoints);
};
const delNodeRelevancy = () => {
  let previousStepIds: number[] = [];
  let nextStepIds: number[] = [];
  props.nodeConfig.relDescDetail?.forEach((item) => {
    if (item.previousStep && !previousStepIds.includes(item.previousStep)) {
      previousStepIds.push(item.previousStep);
    }
    if (item.nextStep && !nextStepIds.includes(item.nextStep)) {
      nextStepIds.push(item.nextStep);
    }
  });
  console.log('删除节点', props.nodeConfig);
  console.log('上', previousStepIds);
  console.log('下', nextStepIds);
};

const delConditionRelevancy = (n: number) => {
  let previousStepIds: number[] = [];
  let nextStepIds: number[] = [];

  if (!props.nodeConfig.conditionNodes?.length) return;
  let treeNode = props.nodeConfig.conditionNodes[n];

  const treeNodeId = Number(treeNode.id);

  if (props.nodeConfig.conditionNodes?.length === 2) {
    getNodeId(props.nodeConfig.conditionNodes[0]);
    getNodeId(props.nodeConfig.conditionNodes[1]);
  } else {
    if (treeNodeId) delNodeIds.value = [treeNodeId];
    if (treeNode.childNode) getNodeId(treeNode.childNode);
  }

  const id = props.nodeConfig.id;
  if (id) previousStepIds.push(id);
  if (props.nodeConfig.childNode?.id)
    nextStepIds.push(props.nodeConfig.childNode?.id);
  let conditions: number[] = [];
  props.nodeConfig.conditionNodes?.forEach((item) => {
    if (item.id && item.id !== treeNode.id) conditions.push(item.id);
  });
  emits('delNode', delNodeIds.value);
  console.log('previousStepIds', previousStepIds);
  console.log('nextStepIds', nextStepIds);
  console.log('delNodeIds.value', delNodeIds.value);
};
const delNodeIds = ref<number[]>([]);
const getNodeId = (data: FlowTree) => {
  const { id, childNode, conditionNodes } = data;
  if (id) delNodeIds.value.push(id);
  if (childNode) getNodeId(childNode);
  if (conditionNodes?.length) conditionNodes.forEach((item) => getNodeId(item));

  return;
};
let bgColors = ['87, 106, 149', '255, 148, 62', '50, 150, 250'];
let placeholderList = ['发起人', '审核人', '抄送人'];
let defaultText = computed(() => {
  const pointType = Number(props.nodeConfig.pointType);
  return placeholderList[pointType];
});
let isInputList = ref<any>([]);
let isInput = ref(false);

const blurEvent = (index: number = -1) => {
  if (index === -1) {
    isInput.value = false;
    props.nodeConfig.pointName = props.nodeConfig.pointName || defaultText;
  } else {
    isInputList.value[index] = false;
    props.nodeConfig.conditionNodes[index].pointName =
      props.nodeConfig.conditionNodes[index].pointName || '条件';
  }
};
// 点击编辑卡片名称
const clickEvent = (index: number = -1) => {
  if (index === -1) {
    isInput.value = true;
  } else {
    isInputList.value[index] = true;
  }
};

// 发起人如果为空，则是所有人可发起审批
let showText = computed(() => {
  // 发起人
  if (props.nodeConfig.pointType == 5)
    return $func.arrToStr(props.nodeConfig.participantList) || '所有人';
  // 审核人
  if (props.nodeConfig.pointType == 1)
    return $func.arrToStr(props.nodeConfig.participantList) || '无审核人';
  // 抄送人
  if (props.nodeConfig.pointType == 2)
    return $func.arrToStr(props.nodeConfig.participantList) || '无审核人';
  return $func.copyerStr(props.nodeConfig);
});
// 条件优先级切换
const arrTransfer = (index: number, type = 1) => {
  //向左-1,向右1
  props.nodeConfig.conditionNodes[index] =
    props.nodeConfig.conditionNodes.splice(
      index + type,
      1,
      props.nodeConfig.conditionNodes[index]
    )[0];
  props.nodeConfig.conditionNodes.map((item: any, index: any) => {
    item.priority = index + 1;
  });
  // resetConditionNodesErr()

  emits('update:nodeConfig', props.nodeConfig);
};
// 删除条件分支
const delTerm = (condition: FlowPanelPoint, index: number) => {
  let conditionId = condition.id;
  let changePoints: FlowPanelPoint[] = []; //删除节点后，优先级需要减一的节点

  props.nodeConfig.conditionNodes?.forEach((point: FlowPanelPoint) => {
    if (
      point.priority &&
      condition.priority &&
      point.priority > condition.priority &&
      point.priority !== 100 &&
      point.id
    ) {
      changePoints.push(point);
    }
  });
  delConditionRelevancy(index);
  // emits("delNode", conditionId, changePoints);
};
const reData = (data: any, addData: any) => {
  if (!data.childNode) {
    data.childNode = addData;
  } else {
    reData(data.childNode, addData);
  }
};
// 设置人员
const setPerson = (priority: any, pointType: any) => {
  if (pointType === 5) {
    // 发起人
    flowStore.setPromoter(true);
    flowStore.setPromoterConfig({
      value: {
        ...JSON.parse(JSON.stringify(props.nodeConfig)),
        ...{
          participantFormat: props.nodeConfig.participantFormat
            ? props.nodeConfig.participantFormat
            : 1
        }
      },
      flag: false,
      id: _uid
    });
  } else if (pointType === 1) {
    // 审核人

    flowStore.setApproverConfig({
      value: {
        ...JSON.parse(JSON.stringify(props.nodeConfig)),
        ...{
          participantFormat: props.nodeConfig.participantFormat
            ? props.nodeConfig.participantFormat
            : 1
        }
      },
      flag: false,
      id: _uid
    });
    flowStore.setApprover(true);
  } else if (pointType === 2) {
    // 抄送人
    flowStore.setCopyer(true);
    flowStore.setCopyerConfig({
      value: JSON.parse(JSON.stringify(props.nodeConfig)),
      flag: false,
      id: _uid
    });
  } else {
    // 条件
    if (priority === 100) return;
    let params = {
      value: JSON.parse(JSON.stringify(props.nodeConfig)),
      priority,
      flag: false,
      id: _uid
    };
    flowStore.setCondition(true);
    flowStore.setConditionsConfig(params);
  }
};
watch(
  () => flowStore.approverConfig1,
  (newVal, oldVal) => {
    if (newVal.flag && newVal.id === _uid) {
      emits('update:nodeConfig', newVal.value.value);
    }
  }
);
watch(
  () => flowStore.conditionsConfig1,
  (newVal, oldVal) => {
    if (newVal.flag && newVal.id === _uid) {
      emits('update:nodeConfig', newVal.value);
    }
  }
);
watch(
  () => flowStore.copyerConfig1,
  (newVal, oldVal) => {
    if (newVal.flag && newVal.id === _uid) {
      emits('update:nodeConfig', newVal.value.value);
    }
  }
);
</script>
